﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;

namespace Rung.EBook.WebSiteAnalizer.Driver
{
    public static class RegexHelper
    {
        public static List<string> GetMatch(string pattern, string input)
        {
            Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            MatchCollection matchs = reg.Matches(input);

            List<string> result = new List<string>();

            if (matchs.Count > 0)
            {
                foreach (Match m in matchs)
                {
                    result.Add(m.Value);
                }

            }
            return result;
        }

        public static DataTable GetCaptures(string pattern, string input, params string[] groupNames)
        {
            Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
            MatchCollection matchs = reg.Matches(input);

            if (matchs.Count > 0 && matchs[0].Groups.Count > 0)
            {
                DataTable rtv = new DataTable();

                for (int i = 0; i < groupNames.Length; i++)
                {
                    rtv.Columns.Add(groupNames[i]);
                }

                for (int i = 0; i < matchs.Count; i++)
                {
                    DataRow row = rtv.NewRow();

                    for (int j = 0; j < groupNames.Length; j++)
                    {
                        row[j] = matchs[i].Groups[groupNames[j]].Value;
                    }
                    rtv.Rows.Add(row);
                }

                return rtv;
            }
            return null;
        }

        /// <summary>
        /// 将指定文本中的指定规则文字转换为指定文字。
        /// </summary>
        /// <param name="pattern">指定规则</param>
        /// <param name="input">待转换文本</param>
        /// <param name="replacement">将符合规则的文字转换为的文字。</param>
        /// <returns></returns>
        public static string Replace(string pattern, string input, string replacement)
        {
            if (replacement == null) replacement = string.Empty;

            Regex reg = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Singleline);
            return reg.Replace(input, replacement);
        }
    }
}
